package com.yiren.dbaa.module.practice_set.line.presenter;

import android.app.Activity;
import android.content.Intent;
import android.util.SparseArray;

import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.currency.bean.CarStateBean;
import com.yiren.backstage.currency.bean.GpsInfoBean;
import com.yiren.backstage.currency.bean.LinePointBean;
import com.yiren.backstage.currency.entity.LineInfoEntity;
import com.yiren.backstage.currency.entity.ProjectEntity;
import com.yiren.backstage.currency.enums.GpsStateEnum;
import com.yiren.backstage.db.dao.cache.DataCache;
import com.yiren.backstage.db.dao.cache.ProjectCache;
import com.yiren.backstage.db.dao.cache.interf.DataCacheStateCallBack;
import com.yiren.backstage.db.dao.controller.GradeDbController;
import com.yiren.dbaa.R;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.module.practice_set.PracticeCarSetActivity;
import com.yiren.dbaa.module.practice_set.line.contract.LineEditContract;
import com.yiren.dbaa.module.practice_set.line.contract.LineHomeContract;
import com.yiren.dbaa.module.practice_set.line.model.LineEditModel;
import com.yiren.dbaa.module.practice_set.line.model.LineHomeModel;
import com.yiren.dbaa.module.practice_set.site.bean.LineDataValBean;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author lwb
 * @date : 2022/6/30 8:55
 * @description: 线路采集
 */
public class LineEditPresenter implements LineEditContract.Presenter {

    private Activity activity;
    private LineEditContract.Model lineEditModel;
    private LineHomeContract.Model lineHomeModel;
    private GradeDbController gradeDbController;
    private UserParamConfigBean userParamConfig;

    public LineEditPresenter(Activity activity) {
        this.activity = activity;
        lineEditModel = new LineEditModel(activity);
        lineHomeModel = new LineHomeModel(activity);
        gradeDbController = GradeDbController.getInstance(false);
        userParamConfig = LoadConfigApi.loadUserParamConfig(activity);
    }

    @Override
    public List<ProjectEntity> getProjectList() {
        List<ProjectEntity> projects = new ArrayList<>();
        if (null != ProjectCache.subjectThreeDayProjects) {
            SparseArray<ProjectEntity> subjectThreeDayProjects = ProjectCache.subjectThreeDayProjects;
            for (int i = 0; i < subjectThreeDayProjects.size(); i++) {
                ProjectEntity projectEntity = subjectThreeDayProjects.get(subjectThreeDayProjects.keyAt(i));
                projects.add(projectEntity);
            }
        }
        return projects;
    }

    @Override
    public void getLinePoints(LineInfoEntity lineInfo, List<LinePointBean> pointList, int pageType, LineEditContract.View view) {
        switch (pageType) {
            case 1:  //刷新完缓存在获取项目
                DataCache.refreshLineInfo(activity, new DataCacheStateCallBack.Callback() {
                    @Override
                    public void success() {
                        activity.runOnUiThread(() -> view.loadProjectList());
                    }
                });
                break;
            case 2:
                lineEditModel.getLinePointFromAll(lineInfo, new CommonCallBack() {
                    @Override
                    public void success(Object result) {
                        pointList.clear();
                        pointList.addAll((List<LinePointBean>) result);
                        view.refreshBaiduMap();
                        activity.runOnUiThread(() -> view.loadProjectList());
                    }
                });
                break;
            case 3:
                int pUserID = lineInfo.getUserId();
                int cUserID = userParamConfig.getUserInfo().getId();
                lineHomeModel.downLoadLinePointData(lineInfo.getName(), lineInfo.getLineVer(), lineInfo.getSiteCode(), pUserID, cUserID, new CommonCallBack() {
                    @Override
                    public void success(Object result) {
                        //本地数据插入
                        LineDataValBean lineDataValBean = (LineDataValBean) result;
                        lineInfo.setPartneModifyVal(lineDataValBean.getPartnerLineData());
                        lineInfo.setCoachModifyVal(lineDataValBean.getCoachLineData());
                        lineEditModel.getLinePoint(lineInfo, new CommonCallBack() {
                            @Override
                            public void success(Object result) {
                                pointList.clear();
                                pointList.addAll((List<LinePointBean>) result);
                                view.refreshBaiduMap();
                            }
                        });
                    }

                    @Override
                    public void fail(String error) {
                        MessageBox.MessageAndVoiceModel(activity, error);
                    }
                });
                break;
        }
    }

    @Override
    public LineInfoEntity setLineInfo() {
        LineInfoEntity lineInfo = new LineInfoEntity();
        lineInfo.setId(UUID.randomUUID().toString());
        lineInfo.setSiteEntity(userParamConfig.getSite());
        lineInfo.setLineVer(0);
        lineInfo.setUserId(userParamConfig.getUserInfo().getId());
        return lineInfo;
    }

    @Override
    public void addPoint(LineInfoEntity lineInfo, List<LinePointBean> pointList, ProjectEntity project, LineEditContract.View view) {
        GpsInfoBean gps = GpsInfoBean.getInstance();
        boolean inGps = gps.getInternalLocationState() == GpsStateEnum.LOCATION_SUCCESS;
        boolean outGps = gps.getExternalLocationState() == GpsStateEnum.LOCATION_SUCCESS;
        if (!inGps && !outGps) {
            MessageBox.show(activity, "GPS定位失败！");
            return;
        }
        if (CarStateBean.getInstance().getSpeed() < 3) {
            //当前为新增线路采集点位或者修改线路中新增或插入点位需要记录方向信息，停车不能采集点位
            MessageBox.show(activity, "停车不能采集，请先行驶车辆再采集线路！");
            return;
        }
        if (pointList.size() == 0) { //采集第一个点位的时候保存线路的位置信息
            lineEditModel.setLineInfoGps(lineInfo);
        }
        LinePointBean linePoint = lineEditModel.setLinePoint(lineInfo, project);
        linePoint.setOrderIndex("" + pointList.size());
        pointList.add(linePoint);
        MessageBox.VoiceModel(activity, linePoint.getProjectInfo().getName());
        view.refreshBaiduMap();
    }

    @Override
    public void insertPoint(LineInfoEntity lineInfo, int currentPointIndex, List<LinePointBean> pointList, ProjectEntity project, LineEditContract.View view) {
        if (currentPointIndex == -1) {
            MessageBox.show(activity, "请先在地图上选择点位！");
            return;
        }
        GpsInfoBean gps = GpsInfoBean.getInstance();
        boolean inGps = gps.getInternalLocationState() == GpsStateEnum.LOCATION_SUCCESS;
        boolean outGps = gps.getExternalLocationState() == GpsStateEnum.LOCATION_SUCCESS;
        if (!inGps && !outGps) {
            MessageBox.show(activity, "GPS定位失败！");
            return;
        }
        if (CarStateBean.getInstance().getSpeed() < 3) {
            MessageBox.show(activity, "停车不能采集，请先行驶车辆再采集线路！");
            return;
        }
        LinePointBean linePoint = lineEditModel.setLinePoint(lineInfo, project);
        linePoint.setOrderIndex("" + (currentPointIndex));
        //中间插入一个点之后，当前位置后面的linePoint的order_index值都要+1
        for (int i = currentPointIndex; i < pointList.size(); i++) {
            LinePointBean lp = pointList.get(i);
            lp.setOrderIndex(lp.getOrderIndex() + 1);
        }
        pointList.add(currentPointIndex, linePoint);
        MessageBox.VoiceModel(activity, linePoint.getProjectInfo().getName());
        view.refreshBaiduMap();
    }

    @Override
    public void modifyLinePoint(String indexStr, int currentPointIndex, List<LinePointBean> pointList, LineEditContract.View view) {
        int index = Integer.parseInt(indexStr);
        if (index > pointList.size()) { //添加到最后
            for (int i = (currentPointIndex + 1); i < pointList.size(); i++) {
                LinePointBean linePoint = pointList.get(i);
                linePoint.setOrderIndex("" + (Integer.parseInt(linePoint.getOrderIndex()) - 1));
            }
            //设置选择点位的order_index
            LinePointBean selectLinePoint = pointList.get(currentPointIndex);
            selectLinePoint.setOrderIndex("" + (pointList.size() - 1));
            pointList.add(selectLinePoint);
            pointList.remove(currentPointIndex);
            view.refreshBaiduMap();
        } else {
            if (currentPointIndex == (index - 1)) {  //修改为自身点位
                return;
            } else if (currentPointIndex < (index - 1)) { //向后修改
                for (int i = (currentPointIndex + 1); i < index; i++) {
                    LinePointBean linePoint = pointList.get(i);
                    linePoint.setOrderIndex("" + (Integer.parseInt(linePoint.getOrderIndex()) - 1));
                }
                //设置选择点位的order_index
                LinePointBean selectLinePoint = pointList.get(currentPointIndex);
                selectLinePoint.setOrderIndex("" + (index - 1));
                pointList.add(index, selectLinePoint);
                pointList.remove(currentPointIndex);
                view.refreshBaiduMap();
            } else {  //向前修改
                for (int i = (index - 1); i < currentPointIndex; i++) {
                    LinePointBean linePoint = pointList.get(i);
                    linePoint.setOrderIndex("" + (Integer.parseInt(linePoint.getOrderIndex()) + 1));
                }
                //设置选择点位的order_index
                LinePointBean selectLinePoint = pointList.get(currentPointIndex);
                selectLinePoint.setOrderIndex("" + (index - 1));
                pointList.remove(currentPointIndex);
                pointList.add(index - 1, selectLinePoint);
                view.refreshBaiduMap();
            }
        }
    }

    @Override
    public void replacePoint(LineInfoEntity lineInfo, int currentPointIndex, List<LinePointBean> pointList, ProjectEntity project, LineEditContract.View view) {
        if (currentPointIndex == -1) {
            MessageBox.show(activity, "请先在地图上选择点位！");
            return;
        }
        LinePointBean selectPoint = pointList.get(currentPointIndex);
        // 设置当前点击的点位
        selectPoint.setPointId(project.getId());
        selectPoint.setProjectInfo(project);
        MessageBox.VoiceModel(activity, project.getName());
        view.refreshBaiduMap();
    }

    @Override
    public void calibrationPoint(int currentPointIndex, List<LinePointBean> pointList, LineEditContract.View view) {
        GpsInfoBean gps = GpsInfoBean.getInstance();
        boolean inGps = gps.getInternalLocationState() == GpsStateEnum.LOCATION_SUCCESS;
        boolean outGps = gps.getExternalLocationState() == GpsStateEnum.LOCATION_SUCCESS;
        if (!inGps && !outGps) {
            MessageBox.show(activity, "GPS定位失败！");
            return;
        }
        if (null == pointList.get(currentPointIndex).getProjectInfo()) {
            MessageBox.show(activity, activity.getString(R.string.no_project));
            return;
        }
        if (CarStateBean.getInstance().getSpeed() < 3) {
            MessageBox.show(activity, "停车不能校准，请先行驶车辆再校准点位！");
            return;
        }
        try {
            LinePointBean selectLinePoint = pointList.get(currentPointIndex);
            lineEditModel.setLinePointGps(selectLinePoint);
            MessageBox.show(activity, activity.getString(R.string.wfa_line_point_correct_message));
            view.refreshBaiduMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deletePoint(int currentPointIndex, List<LinePointBean> pointList, LineEditContract.View view) {
        pointList.remove(currentPointIndex);
        view.refreshBaiduMap();
    }

    @Override
    public void saveCoachModify(LineInfoEntity lineInfo, List<LinePointBean> tempLinePoints) {
        lineEditModel.setCoachModify(lineInfo, tempLinePoints);
    }

    @Override
    public void saveLineAndLinePoint(LineInfoEntity lineInfo, int pageType) {
        if (pageType == 1) {   // 新增线路
            if (!gradeDbController.insertOrReplace(lineInfo)) {  //新增线路失败
                LoadDialog.dismiss(activity);
                MessageBox.show(activity, "新增线路失败!");
            }
        } else if (pageType == 2) {   // 修改线路
            if (!gradeDbController.update(lineInfo)) {  // 修改线路失败  首页
                LoadDialog.dismiss(activity);
                MessageBox.show(activity, "修改线路失败!");
            }
        }
        //线路新增或修改成功
        LoadDialog.dismiss(activity);
        if (pageType == 1) {
            MessageBox.show(activity, "保存成功！");
        } else {
            MessageBox.show(activity, "修改成功！");
        }
        DataCache.refreshLineInfo(activity, new DataCacheStateCallBack.Callback() {
            @Override
            public void success() {
                activity.startActivity(new Intent(activity, PracticeCarSetActivity.class));
                activity.finish();
            }
        });
    }

}